package com.rich.live.service.impl;


import com.rich.live.mapper.LiveFollowerMapper;

import com.rich.live.service.LiveFollowerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


/**
 * @author hu
 * @version 1.0
 * @date 2021/08/14 18:51
 */
@Service
public class LiveFollowerServiceImpl implements LiveFollowerService {

    @Autowired
    private LiveFollowerMapper liveFollowerMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 添加关注人
     * @param id
     * @param uid
     * @param url
     */
    @Override
    public void addLiveFollower(Long id, Long uid, String url) {
        liveFollowerMapper.addLiveFollower(id, uid, url);
    }

    /**
     * 点赞数量
     *
     * @param id
     * @param num
     */
    @Override
    public void likeNum(Long id, Integer num) {

        Integer likeNum;

        likeNum = (Integer) redisTemplate.boundHashOps("like").get(id);
        if (likeNum == null) {
            //获得点赞数
            likeNum = liveFollowerMapper.likeNum(id);
            likeNum = likeNum + 1;
            //存入redis
            redisTemplate.boundHashOps("like").put(id, likeNum);
        } else {
            likeNum = likeNum + 1;
            redisTemplate.boundHashOps("like").put(id, likeNum);
        }

    }


    /**
     * 定时器，每隔五分钟获取点赞数，修改
     */
    @Scheduled(cron = "*/20 * * * * ?")
    public void updateLikeNum() {
        HashMap<Long, Integer> like = (HashMap<Long, Integer>) redisTemplate.boundHashOps("like").entries();
        //遍历获得键，值，去数据库修改
        for (Map.Entry<Long, Integer> map : like.entrySet()) {
            liveFollowerMapper.likeEnd(map.getKey(), map.getValue());
        }
    }

}
